package com.filter;

import com.alibaba.fastjson.JSON;
import com.common.BaseContext;
import com.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")//
public class LoginCheckFilter implements Filter{
    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();//路径匹配器支持通配符
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        String str = request.getRequestURI();
        //设置允许通过的请求路径
        String[] strings=new String[]{"/employee/login","/employee/logout","/backend/**","/front/**","/common/**","static/backend/page/demo/upload.html"
        ,"/user/sendMsg","/user/login", "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        //判断是否拦截
        boolean check =check(strings, str);
        //不需要拦截，放行
        if (check){
            filterChain.doFilter(request,response);
            return;
        }
        //需要拦截，判断是否登陆
        if (request.getSession().getAttribute("id")!=null){
            //设置当前操作者的id
            Long id=(Long) request.getSession().getAttribute("id");
            BaseContext.setCurrentId(id);
//            long id = Thread.currentThread().getId();
//            log.info("线程为："+id);
            filterChain.doFilter(request,response);//通过查询登陆成功时添加的session来判断
            return;
        }
        //  移动端判断
        if (request.getSession().getAttribute("user")!=null){
            //设置当前操作者的id
            Long userId = (Long)request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
//            long id = Thread.currentThread().getId();
//            log.info("线程为："+id);
            filterChain.doFilter(request,response);//通过查询登陆成功时添加的session来判断
            return;
        }else {
            response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));//返回JSON数据(将java对象转换成Json格式返回给前端)
            return;
        }
    }
    //封装方法遍历，判断是否需要拦截
    public  boolean check(String[] strings,String str){
        for (String string : strings) {
            boolean result = PATH_MATCHER.match(string, str);
            if (result){
                return true;
            }
        }
        return false;
    }
}
